//
//  LoadingView.m
//  LoadingView
//
//  Created by 咖啡邦-2 on 15/10/28.
//  Copyright © 2015年 kafeibang. All rights reserved.
//

#import "LoadingView.h"
#import "UIImage+GIF.h"
#import "UIColor+Extension.h"

@implementation LoadingView

+ (instancetype)sharedLoading {
    static LoadingView *instance = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[LoadingView alloc] initWithFrame:CGRectMake(0, 0, kWindowW, kWindowH)];
    });
    
    return instance;
}

- (id)initWithFrame:(CGRect)frame {
    
    self = [super initWithFrame:frame];
    if (self) {
        UIView *views=[[UIView alloc] initWithFrame:CGRectMake(0,0, kWindowW, kWindowH)];
        views.userInteractionEnabled = NO;
        views.backgroundColor = [UIColor clearColor];
        UIView *logview=[[UIView alloc] initWithFrame:CGRectMake(kWindowW/2-75,kWindowH/2-75, 150,150)];
        [logview setBackgroundColor:[UIColor clearColor]];
        logview.layer.cornerRadius =5;
        logview.layer.masksToBounds = YES;
        [logview addSubview:self.loadingImageView];
        UITapGestureRecognizer *singleTap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(maskViewClick)];
        [views addGestureRecognizer:singleTap];
        
        [self addSubview:views];
        [self addSubview:logview];
    }
    return self;
}

// 懒加载
- (UIImageView *)loadingImageView {
    if (!_loadingImageView) {
        _loadingImageView = [[UIImageView alloc] init];
        _loadingImageView.frame =CGRectMake(0,0,150,150);
        NSString *path = [[NSBundle mainBundle] pathForResource:@"loading" ofType:@"gif"];
        NSData *data = [NSData dataWithContentsOfFile:path];
        UIImage *image = [UIImage sd_animatedGIFWithData:data];
        _loadingImageView.image = image;
    }
    return _loadingImageView;
}

-(void)maskViewClick {
    [[LoadingView sharedLoading] removeFromSuperview];
}

/**
 开始加载
 */
+ (void)addLoadingView {
    [[UIApplication sharedApplication].keyWindow addSubview:[LoadingView sharedLoading]];
}

/**
 结束加载
 */
+ (void)removeLoadingView {
    [[LoadingView sharedLoading] removeFromSuperview];
}


/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end
